/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Labsystem.Usuarios;

import Entidades.Usuario;
import Labsystem.DaoImpl;
import java.awt.Toolkit;
import java.util.List;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;

/**
 *
 * @author belen
 */
public class AdminUsuario extends javax.swing.JDialog {

    /**
     * Creates new form AdminUsuario
     */
    private DaoImpl dao = new DaoImpl();
    
    public AdminUsuario(java.awt.Frame parent, String title, boolean modal) {
        super(parent,title, modal);
        initComponents();
        eliminarButton.setEnabled(false);
        modificarButton.setEnabled(false);
        cargoList.setEnabled(false);
        consultaTextField.setEnabled(false);
        ejecutarQueryTabla("from Usuario");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        buttonGroup3 = new javax.swing.ButtonGroup();
        buttonGroup4 = new javax.swing.ButtonGroup();
        buttonGroup5 = new javax.swing.ButtonGroup();
        jRadioButton1 = new javax.swing.JRadioButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaConsulta = new javax.swing.JTable();
        agregarButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        consultaComboBox = new javax.swing.JComboBox();
        consultaTextField = new javax.swing.JTextField();
        modificarButton = new javax.swing.JButton();
        eliminarButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        cargoList = new javax.swing.JList();

        jRadioButton1.setText("jRadioButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setBackground(new java.awt.Color(224, 224, 224));

        jPanel1.setBackground(new java.awt.Color(223, 223, 223));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Usuarios", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Ubuntu", 1, 24), new java.awt.Color(20, 48, 106))); // NOI18N

        tablaConsulta.setFont(new java.awt.Font("Ubuntu", 0, 14)); // NOI18N
        tablaConsulta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tablaConsulta.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaConsultaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tablaConsulta);

        agregarButton.setFont(new java.awt.Font("Ubuntu", 1, 14)); // NOI18N
        agregarButton.setText("Agregar");
        agregarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                agregarButtonActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Ubuntu", 1, 14)); // NOI18N
        jLabel1.setText("Filtrar por:");

        consultaComboBox.setFont(new java.awt.Font("Ubuntu", 1, 14)); // NOI18N
        consultaComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Alias", "Nombre", "Apellido", "Cargo" }));
        consultaComboBox.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                consultaComboBoxMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                consultaComboBoxMousePressed(evt);
            }
        });
        consultaComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                consultaComboBoxActionPerformed(evt);
            }
        });

        consultaTextField.setFont(new java.awt.Font("Ubuntu", 0, 14)); // NOI18N
        consultaTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                consultaTextFieldActionPerformed(evt);
            }
        });
        consultaTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                consultaTextFieldKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                consultaTextFieldKeyTyped(evt);
            }
        });

        modificarButton.setFont(new java.awt.Font("Ubuntu", 1, 14)); // NOI18N
        modificarButton.setText("Modificar");
        modificarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modificarButtonActionPerformed(evt);
            }
        });

        eliminarButton.setFont(new java.awt.Font("Ubuntu", 1, 14)); // NOI18N
        eliminarButton.setText("Eliminar");
        eliminarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eliminarButtonActionPerformed(evt);
            }
        });

        cargoList.setFont(new java.awt.Font("Ubuntu", 1, 14)); // NOI18N
        cargoList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Recepcionista", "Bioquímico", "Flebotomista", "Administrador" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        cargoList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cargoListMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(cargoList);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGap(6, 6, 6)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(consultaComboBox, 0, 123, Short.MAX_VALUE)
                        .addComponent(consultaTextField)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 495, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(agregarButton)
                        .addGap(107, 107, 107)
                        .addComponent(modificarButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(eliminarButton)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(consultaComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addComponent(consultaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(agregarButton)
                    .addComponent(modificarButton)
                    .addComponent(eliminarButton))
                .addGap(25, 25, 25))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 58, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void agregarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_agregarButtonActionPerformed
        // TODO add your handling code here:
        new AddUsuario(this,"Agregar Usuario", true).setVisible(true);
        ejecutarQueryTabla("from Usuario");
    }//GEN-LAST:event_agregarButtonActionPerformed

    private void modificarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modificarButtonActionPerformed
        // TODO add your handling code here:
        int fila = tablaConsulta.getSelectedRow();
        if (fila != -1){//si se seleccionó una fila
            String id= tablaConsulta.getValueAt(fila, 0).toString();
             new UpdUsuario(this,"Modificar Usuario",true, id).setVisible(true);
               
        }else{
            JOptionPane.showMessageDialog(this, "No hay registro seleccionado");
            
        }
        ejecutarQueryTabla("from Usuario");
         
    }//GEN-LAST:event_modificarButtonActionPerformed

    private void consultaTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_consultaTextFieldKeyReleased
        // TODO add your handling code here:
        
            //cargoList.setVisible(false);
        
        
        
        if(consultaComboBox.getSelectedItem().toString()=="Alias"){
            //cargoList.setVisible(false);
            if(!consultaTextField.getText().isEmpty()){
                ejecutarQueryTabla("from Usuario a where lower(a.nick) like lower('"+consultaTextField.getText()+"%')");
                
            }
            if(consultaTextField.getText().isEmpty()){
                ejecutarQueryTabla("from Usuario");
            }
        }
        
        
         if(consultaComboBox.getSelectedItem().toString()=="Nombre"){
             //cargoList.setVisible(false);
           if(!consultaTextField.getText().isEmpty()){
               ejecutarQueryTabla("from Usuario a where lower(a.nombre) like lower('"+consultaTextField.getText()+"%')");
                
            }else{
                ejecutarQueryTabla("from Usuario");
            }
          }
         
         if(consultaComboBox.getSelectedItem().toString()=="Apellido"){
            //cargoList.setVisible(false);
            if(!consultaTextField.getText().isEmpty()){
                 ejecutarQueryTabla("from Usuario a where lower(a.apellido) like lower('"+consultaTextField.getText()+"%')");

             }else{
                 ejecutarQueryTabla("from Usuario");
          } 
         }
         
         
        
        
    }//GEN-LAST:event_consultaTextFieldKeyReleased

    private void eliminarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eliminarButtonActionPerformed
        // TODO add your handling code here:
        int[] filas = tablaConsulta.getSelectedRows();
        if (filas[0] != -1){//si se seleccionó por lo menos una fila
            int var = JOptionPane.showOptionDialog(this, "Está Seguro que desea eliminar?","OPCIONES", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{"SI","NO"}, "SI");
             if(var != -1){ 
                 if((var +1)==1){ //si es si
                    for (int f : filas){
                       String idRegistro = tablaConsulta.getValueAt(f,0 ).toString();
                       List listUsuario =  dao.ejecutarQuery("from Usuario a where a.idUsuario = "+idRegistro);
                       Usuario registroUsuario = (Usuario) listUsuario.get(0);
                       dao.eliminar(registroUsuario);
                                             
                    }
                    ejecutarQueryTabla("from Usuario");
                 }
              }
         }else{// si no seleccionó filas
            JOptionPane.showMessageDialog(this, "No hay registro seleccionado");
            
        }
        
               
    }//GEN-LAST:event_eliminarButtonActionPerformed

    private void tablaConsultaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaConsultaMouseClicked
        // TODO add your handling code here:
        
        if (tablaConsulta.isFocusOwner()){
            eliminarButton.setEnabled(true);
            modificarButton.setEnabled(true);
        }
    }//GEN-LAST:event_tablaConsultaMouseClicked

    private void cargoListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cargoListMouseClicked
        // TODO add your handling code here:
        if(consultaComboBox.getSelectedItem().toString()=="Cargo"){
              
           ejecutarQueryTabla("from Usuario a where lower(a.cargo) like lower('"+cargoList.getSelectedValue().toString()+"%')");

             
        }
        
        
    }//GEN-LAST:event_cargoListMouseClicked

    private void consultaComboBoxMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_consultaComboBoxMousePressed
        // TODO add your handling code here:
        
    }//GEN-LAST:event_consultaComboBoxMousePressed

    private void consultaTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_consultaTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_consultaTextFieldActionPerformed

    private void consultaTextFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_consultaTextFieldKeyTyped
        // TODO add your handling code here:
        
        
    }//GEN-LAST:event_consultaTextFieldKeyTyped

    private void consultaComboBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_consultaComboBoxMouseClicked
        // TODO add your handling code here:
        if(consultaComboBox.getSelectedItem().toString()=="Alias"){
            cargoList.setEnabled(false);
            consultaTextField.setEnabled(true);
            
        }
        
        
         if(consultaComboBox.getSelectedItem().toString()=="Nombre"){
             cargoList.setEnabled(false);
             consultaTextField.setEnabled(true);
           
          }
         
         if(consultaComboBox.getSelectedItem().toString()=="Apellido"){
            cargoList.setEnabled(false);
             consultaTextField.setEnabled(true);
            
         }
          if(consultaComboBox.getSelectedItem().toString()=="Cargo"){
            cargoList.setEnabled(true);
            consultaTextField.setEnabled(false);
            
         }
    }//GEN-LAST:event_consultaComboBoxMouseClicked

    private void consultaComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_consultaComboBoxActionPerformed
        // TODO add your handling code here:
        if(consultaComboBox.getSelectedItem().toString()=="Alias"){
            cargoList.setEnabled(false);
            consultaTextField.setEnabled(true);
            
        }
        
        
         if(consultaComboBox.getSelectedItem().toString()=="Nombre"){
             cargoList.setEnabled(false);
             consultaTextField.setEnabled(true);
           
          }
         
         if(consultaComboBox.getSelectedItem().toString()=="Apellido"){
            cargoList.setEnabled(false);
             consultaTextField.setEnabled(true);
            
         }
          if(consultaComboBox.getSelectedItem().toString()=="Cargo"){
            cargoList.setEnabled(true);
            consultaTextField.setEnabled(false);
            
         }
        
    }//GEN-LAST:event_consultaComboBoxActionPerformed

    private void verResultadoTabla(List listaResultado) {
    Vector<String> cabeceraTabla = new Vector<String>();
    Vector datosTabla = new Vector();
    cabeceraTabla.add("Id");
    cabeceraTabla.add("Cédula");
    cabeceraTabla.add("Nombre"); 
    cabeceraTabla.add("Apellido");
    cabeceraTabla.add("Departamento");
    cabeceraTabla.add("Sucursal");
    cabeceraTabla.add("Cargo");
    cabeceraTabla.add("Direccion");
    cabeceraTabla.add("Telefono");
    cabeceraTabla.add("Email");
    cabeceraTabla.add("Alias");
      
    for(Object o: listaResultado) {
        Usuario usuario = (Usuario) o;
        Vector<Object> fila= new Vector<Object>();
        fila.add(usuario.getIdUsuario());
        fila.add(usuario.getCedula());
        fila.add(usuario.getNombre());
        fila.add(usuario.getApellido());
        fila.add(usuario.getDepartamento().getNombre());
        fila.add(usuario.getSucursal().getNombre());
        fila.add(usuario.getCargo());
        fila.add(usuario.getDireccion());
        fila.add(usuario.getTelefono());
        fila.add(usuario.getCorreo());
        fila.add(usuario.getNick());
             
        datosTabla.add(fila);
    }
    tablaConsulta.setModel(new DefaultTableModel(datosTabla, cabeceraTabla));
}
    private void ejecutarQueryTabla(String hql) {
    
        
        List resultado=dao.ejecutarQuery(hql);
        verResultadoTabla(resultado);
        
    /*}catch (HibernateException he) {
        he.printStackTrace();
    }*/
}
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AdminUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AdminUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AdminUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AdminUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                AdminUsuario dialog = new AdminUsuario(new javax.swing.JFrame(),"Usuarios", true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton agregarButton;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.ButtonGroup buttonGroup3;
    private javax.swing.ButtonGroup buttonGroup4;
    private javax.swing.ButtonGroup buttonGroup5;
    private javax.swing.JList cargoList;
    private javax.swing.JComboBox consultaComboBox;
    private javax.swing.JTextField consultaTextField;
    private javax.swing.JButton eliminarButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton modificarButton;
    private javax.swing.JTable tablaConsulta;
    // End of variables declaration//GEN-END:variables
}
